package main
//本课程源码见：https://github.com/owenliang/go-websocket
// 实战弹幕源码见：https://github.com/owenliang/go-push

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"websocket/impl"
)

var(
	upgrader = websocket.Upgrader{
		//允许跨域
		CheckOrigin:func(r *http.Request)bool{
			return true
		},
	}
)

func HandBuiness(conn *impl.Connection) {
	var (
		data []byte
		err  error
	)
	for {
		log.Println("handBuiness:")
		if data, err = conn.ReadMessage(); err != nil {
			fmt.Println("read fail")
			break
		}
		if err = conn.WriteMessage(data); err != nil {
			fmt.Println("write fail")
			break
		}
	}
}


func wsHandler(w http.ResponseWriter,r *http.Request){
	var(
		wsConn *websocket.Conn
		err error
		conn *impl.Connection
	)
	log.Println("Hello")
	if wsConn,err = upgrader.Upgrade(w,r,nil);err!=nil{
		panic(err)
		return
	}
	if conn,err = impl.InitConnection(wsConn);err!=nil{
		defer conn.Close()
	}
	go HandBuiness(conn)
}

func main(){
	http.HandleFunc("/ws",wsHandler)
	http.ListenAndServe("0.0.0.0:7777",nil)
}
